<template>
  <div class="user-profile-container">
    <div class="container">
      <!-- 用户信息头部 -->
      <div class="user-header">
        <el-avatar :size="100" :src="userAvatar">{{ currentUser?.username?.[0] }}</el-avatar>
        <div class="user-basic-info">
          <h1 class="username">{{ currentUser?.username }}</h1>
          <p class="user-bio">{{ currentUser?.bio || '这个人很懒，什么都没有留下' }}</p>
          <div class="user-stats">
          <div class="stat-item">
            <span class="stat-value">{{ videoCount }}</span>
            <span class="stat-label">发布视频</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ likeCount }}</span>
            <span class="stat-label">获赞</span>
          </div>
          <div class="stat-item" @click="handleOpenFollowers" style="cursor: pointer;">
            <span class="stat-value">{{ fansCount }}</span>
            <span class="stat-label">粉丝</span>
          </div>
          <div class="stat-item" @click="handleOpenFollowing" style="cursor: pointer;">
            <span class="stat-value">{{ followingCount }}</span>
            <span class="stat-label">关注</span>
          </div>
        </div>
        </div>
        <el-button type="primary" class="edit-profile-btn" @click="showEditProfile = true">
          <el-icon><Edit /></el-icon> 编辑资料
        </el-button>
      </div>

      <!-- 导航选项卡 -->
      <el-tabs v-model="activeTab" class="user-tabs">
        <el-tab-pane label="我的视频" name="videos">
          <div class="video-grid" v-if="userVideos.length > 0">
            <el-card 
              v-for="video in userVideos" 
              :key="video.video_id"
              class="video-card"
              @click="goToVideoDetail(video.video_id)"
            >
              <div class="video-cover">
                <img 
                  :src="video.video_cover || '/placeholder.svg?size=300x180'" 
                  :alt="video.video_title"
                  class="cover-image"
                >
                <span class="view-count"><el-icon><View /></el-icon> {{ video.view_count }}</span>
              </div>
              <div class="video-info">
                <h3 class="video-title">{{ video.video_title }}</h3>
                <div class="video-meta">
                  <span><el-icon><Calendar /></el-icon> {{ formatDate(video.video_time) }}</span>
                  <div class="video-stats">
                    <span><el-icon><StarFilled /></el-icon> {{ video.like_count }}</span>
                    <span><el-icon><ChatDotRound /></el-icon> {{ getCommentCount(video.video_id) }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
          <el-empty v-else description="还没有发布视频" />
        </el-tab-pane>
        
        <el-tab-pane label="我的收藏" name="collections">
          <div class="video-grid" v-if="userCollections.length > 0">
            <el-card 
              v-for="video in userCollections" 
              :key="video.video_id"
              class="video-card"
              @click="goToVideoDetail(video.video_id)"
            >
              <div class="video-cover">
                <img 
                  :src="video.video_cover || '/placeholder.svg?size=300x180'" 
                  :alt="video.video_title"
                  class="cover-image"
                >
                <span class="view-count"><el-icon><View /></el-icon> {{ video.view_count }}</span>
              </div>
              <div class="video-info">
                <h3 class="video-title">{{ video.video_title }}</h3>
                <div class="video-meta">
                  <span class="author">{{ getUserName(video.user_id) }}</span>
                  <div class="video-stats">
                    <span><el-icon><StarFilled /></el-icon> {{ video.like_count }}</span>
                    <span><el-icon><ChatDotRound /></el-icon> {{ getCommentCount(video.video_id) }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
          <el-empty v-else description="还没有收藏视频" />
        </el-tab-pane>
        
        <el-tab-pane label="我的点赞" name="likes">
          <div class="video-grid" v-if="userLikes.length > 0">
            <el-card 
              v-for="video in userLikes" 
              :key="video.video_id"
              class="video-card"
              @click="goToVideoDetail(video.video_id)"
            >
              <div class="video-cover">
                <img 
                  :src="video.video_cover || '/placeholder.svg?size=300x180'" 
                  :alt="video.video_title"
                  class="cover-image"
                >
                <span class="view-count"><el-icon><View /></el-icon> {{ video.view_count }}</span>
              </div>
              <div class="video-info">
                <h3 class="video-title">{{ video.video_title }}</h3>
                <div class="video-meta">
                  <span class="author">{{ getUserName(video.user_id) }}</span>
                  <div class="video-stats">
                    <span><el-icon><StarFilled /></el-icon> {{ video.like_count }}</span>
                    <span><el-icon><ChatDotRound /></el-icon> {{ getCommentCount(video.video_id) }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
          <el-empty v-else description="还没有点赞视频" />
        </el-tab-pane>
        
        <el-tab-pane label="我的评论" name="comments">
          <div class="comments-list" v-if="userComments.length > 0">
            <div v-for="comment in userComments" :key="comment.comment_id" class="comment-item">
              <div class="comment-content">
                <p class="comment-text">{{ comment.content }}</p>
                <div class="comment-meta">
                  <span class="comment-time">{{ formatTime(comment.comment_time) }}</span>
                  <button class="go-to-video-btn" @click="goToVideoDetail(comment.video_id)">
                    查看视频
                  </button>
                </div>
              </div>
            </div>
          </div>
          <el-empty v-else description="还没有发表评论" />
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 编辑资料对话框 -->
    <el-dialog
      v-model="showEditProfile"
      title="编辑个人资料"
      width="500px"
      :before-close="handleCloseEdit"
    >
      <el-form 
        :model="editForm" 
        :rules="editRules" 
        ref="editFormRef"
        class="edit-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="个人简介" prop="bio">
          <el-input
            v-model="editForm.bio"
            type="textarea"
            :rows="3"
            placeholder="请输入个人简介"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleUpdateProfile">保存</el-button>
          <el-button @click="showEditProfile = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    
    <!-- 粉丝列表对话框 -->
    <el-dialog v-model="showFollowersDialog" title="粉丝列表" width="500px">
      <div v-if="followersList.length > 0" class="user-list">
        <div v-for="user in followersList" :key="user.user_id" class="user-item">
          <div class="user-info">
            <div class="user-avatar" :style="{backgroundColor: userAvatar}">{{ user.username.charAt(0) }}</div>
            <div class="user-details">
              <div class="user-name">{{ user.username }}</div>
              <div class="user-bio">{{ user.bio || '暂无简介' }}</div>
            </div>
          </div>
        </div>
      </div>
      <el-empty v-else description="暂无粉丝" />
    </el-dialog>
    
    <!-- 关注列表对话框 -->
    <el-dialog v-model="showFollowingDialog" title="关注列表" width="500px">
      <div v-if="followingList.length > 0" class="user-list">
        <div v-for="user in followingList" :key="user.user_id" class="user-item">
          <div class="user-info">
            <div class="user-avatar" :style="{backgroundColor: userAvatar}">{{ user.username.charAt(0) }}</div>
            <div class="user-details">
              <div class="user-name">{{ user.username }}</div>
              <div class="user-bio">{{ user.bio || '暂无简介' }}</div>
            </div>
          </div>
        </div>
      </div>
      <el-empty v-else description="暂无关注" />
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../store/userStore'
import { useVideoStore } from '../store/videoStore'
import { Edit, View, Calendar, StarFilled, ChatDotRound, UserFilled } from '@element-plus/icons-vue'
import { ElAvatar, ElButton, ElTabs, ElTabPane, ElCard, ElEmpty, ElDialog, ElForm, ElFormItem, ElInput, ElMessage } from 'element-plus'

export default {
  name: 'UserProfileView',
  components: {
    ElAvatar,
    ElButton,
    ElTabs,
    ElTabPane,
    ElCard,
    ElEmpty,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    Edit,
    View,
    Calendar,
    StarFilled,
    ChatDotRound
  },
  setup() {
    const router = useRouter()
    const userStore = useUserStore()
    const videoStore = useVideoStore()
    // 初始化时检查URL查询参数
    const initialTab = router.currentRoute.value.query.tab || 'videos'
    const activeTab = ref(initialTab)
    const showEditProfile = ref(false)
    const showFollowersDialog = ref(false)
    const showFollowingDialog = ref(false)
    const editFormRef = ref(null)
    const commentsMap = ref({})
    
    const userVideos = ref([])
    const userCollections = ref([])
    const userLikes = ref([])
    const userComments = ref([])
    const followersList = ref([])
    const followingList = ref([])
    const followersCount = ref(0)
    const followingCountVal = ref(0)
    
    const editForm = reactive({
      username: '',
      email: '',
      bio: ''
    })
    
    const editRules = reactive({
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符之间', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
      ]
    })

    onMounted(async () => {
      if (!userStore.isLoggedIn) {
        router.push('/login')
        return
      }
      // 先加载所有视频，然后再加载用户个人资料和统计数据
      await videoStore.fetchVideos()
      await loadUserProfile()
      await loadFollowStats()
    })

    watch(() => userStore.currentUser, (newUser) => {
      if (newUser) {
        updateEditForm(newUser)
      }
    })

    const loadUserProfile = async () => {
      try {
        // 加载用户相关数据
        await Promise.all([
          loadUserVideos(),
          loadUserCollections(),
          loadUserLikes(),
          loadUserComments(),
          loadComments()
        ])
      } catch (error) {
        console.error('加载用户资料失败:', error)
      }
    }

    const loadUserVideos = async () => {
      try {
        // 从视频store中获取用户发布的视频
        userVideos.value = videoStore.videos.filter(
          video => video.user_id === userStore.currentUser.user_id
        )
      } catch (error) {
        console.error('加载用户视频失败:', error)
      }
    }

    const loadUserCollections = async () => {
      try {
        // 获取用户收藏的视频ID列表
        const collections = await userStore.getMyCollections()
        const videoIds = collections.map(item => item.video_id)
        
        // 获取完整的视频信息
        userCollections.value = videoStore.videos.filter(
          video => videoIds.includes(video.video_id)
        )
      } catch (error) {
        console.error('加载用户收藏失败:', error)
      }
    }
    
    // 获取粉丝列表
    const loadFollowersList = async () => {
      try {
        if (!userStore.currentUser) return
        
        // 获取所有关注关系
        const response = await fetch('http://localhost:3000/userFollows?followed_id=' + userStore.currentUser.user_id)
        const follows = await response.json()
        
        // 更新粉丝计数
        followersCount.value = follows.length
        
        // 获取粉丝用户信息
        const followerIds = follows.map(f => f.follower_id)
        const usersResponse = await fetch('http://localhost:3000/users')
        const allUsers = await usersResponse.json()
        
        // 筛选出粉丝用户
        followersList.value = allUsers.filter(user => followerIds.includes(user.user_id))
      } catch (error) {
        console.error('加载粉丝列表失败:', error)
        // 模拟数据
        followersList.value = [
          { user_id: 2, username: 'lisi', avatar: '', bio: 'B站资深up主' },
          { user_id: 3, username: '王五', avatar: '', bio: '美食爱好者' }
        ]
        followersCount.value = followersList.value.length
      }
    }
    
    // 获取关注列表
    const loadFollowingList = async () => {
      try {
        if (!userStore.currentUser) return
        
        // 获取所有关注关系
        const response = await fetch('http://localhost:3000/userFollows?follower_id=' + userStore.currentUser.user_id)
        const follows = await response.json()
        
        // 更新关注计数
        followingCountVal.value = follows.length
        
        // 获取被关注用户信息
        const followingIds = follows.map(f => f.followed_id)
        const usersResponse = await fetch('http://localhost:3000/users')
        const allUsers = await usersResponse.json()
        
        // 筛选出关注用户
        followingList.value = allUsers.filter(user => followingIds.includes(user.user_id))
      } catch (error) {
        console.error('加载关注列表失败:', error)
        // 模拟数据
        followingList.value = [
          { user_id: 2, username: 'lisi', avatar: '', bio: 'B站资深up主' },
          { user_id: 3, username: '王五', avatar: '', bio: '美食爱好者' }
        ]
        followingCountVal.value = followingList.value.length
      }
    }

    const loadUserLikes = async () => {
      try {
        // 获取用户点赞的视频ID列表
        const likes = await userStore.getMyLikes()
        const videoIds = likes.map(item => item.video_id)
        
        // 获取完整的视频信息
        userLikes.value = videoStore.videos.filter(
          video => videoIds.includes(video.video_id)
        )
      } catch (error) {
        console.error('加载用户点赞失败:', error)
      }
    }

    const loadUserComments = async () => {
      try {
        // 获取用户评论
        userComments.value = await userStore.getMyComments()
      } catch (error) {
        console.error('加载用户评论失败:', error)
      }
    }

    const loadComments = async () => {
      try {
        const comments = await fetch('http://localhost:3000/comments')
        const data = await comments.json()
        // 统计每个视频的评论数
        data.forEach(comment => {
          if (!commentsMap.value[comment.video_id]) {
            commentsMap.value[comment.video_id] = 0
          }
          commentsMap.value[comment.video_id]++
        })
      } catch (error) {
        console.error('加载评论统计失败:', error)
      }
    }

    const updateEditForm = (user) => {
      editForm.username = user.username || ''
      editForm.email = user.email || ''
      editForm.bio = user.bio || ''
    }

    const handleCloseEdit = () => {
      // 重置表单
      if (editFormRef.value) {
        editFormRef.value.resetFields()
      }
      updateEditForm(userStore.currentUser)
    }

    const handleUpdateProfile = async () => {
      if (!editFormRef.value) return
      
      try {
        await editFormRef.value.validate()
        
        // 调用更新用户信息的方法
        await userStore.updateUserInfo({
          username: editForm.username,
          email: editForm.email,
          bio: editForm.bio
        })
        
        ElMessage.success('个人资料更新成功')
        showEditProfile.value = false
      } catch (error) {
        console.error('更新个人资料失败:', error)
        ElMessage.error('更新失败，请稍后重试')
      }
    }

    const goToVideoDetail = (videoId) => {
      router.push(`/video/${videoId}`)
    }

    const getUserName = (userId) => {
      const userMap = {
        1: '张三',
        2: '李四',
        3: '王五',
        4: '赵六',
        5: '测试用户1',
        6: '测试用户2'
      }
      return userMap[userId] || '未知用户'
    }

    const getCommentCount = (videoId) => {
      return commentsMap.value[videoId] || 0
    }

    const formatDate = (dateString) => {
      if (!dateString) return ''
      return new Date(dateString).toLocaleDateString('zh-CN')
    }

    const formatTime = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      const now = new Date()
      const diff = now - date
      
      if (diff < 3600000) {
        return Math.floor(diff / 60000) + '分钟前'
      } else if (diff < 86400000) {
        return Math.floor(diff / 3600000) + '小时前'
      } else if (diff < 604800000) {
        return Math.floor(diff / 86400000) + '天前'
      } else {
        return date.toLocaleDateString('zh-CN')
      }
    }

    // 计算属性
    const currentUser = computed(() => userStore.currentUser)
    const userAvatar = computed(() => {
      const avatarColors = ['#f56c6c', '#e6a23c', '#5cb87a', '#1989fa', '#6f7ad3', '#909399']
      const index = currentUser.value?.user_id ? (currentUser.value.user_id - 1) % avatarColors.length : 0
      return avatarColors[index]
    })
    
    const videoCount = computed(() => userVideos.value.length)
    const likeCount = computed(() => {
      // 计算用户获得的总赞数
      if (!userStore.currentUser || !videoStore.videos.length) return 0
      
      // 从videoStore中获取用户的视频并计算总赞数
      const userVideoList = videoStore.videos.filter(video => 
        video.user_id === userStore.currentUser.user_id
      )
      
      return userVideoList.reduce((total, video) => total + (video.like_count || 0), 0)
    })
    const fansCount = computed(() => followersCount.value)
    const followingCount = computed(() => followingCountVal.value)
    
    // 加载关注和粉丝计数
    const loadFollowStats = async () => {
      try {
        if (!userStore.currentUser) return
        
        // 加载粉丝数
        const followersResponse = await fetch('http://localhost:3000/userFollows?followed_id=' + userStore.currentUser.user_id)
        const followers = await followersResponse.json()
        followersCount.value = followers.length
        
        // 加载关注数
        const followingResponse = await fetch('http://localhost:3000/userFollows?follower_id=' + userStore.currentUser.user_id)
        const following = await followingResponse.json()
        followingCountVal.value = following.length
      } catch (error) {
        console.error('加载关注统计失败:', error)
        // 使用默认值
        followersCount.value = 2
        followingCountVal.value = 2
      }
    }
    
    // 打开粉丝列表
    const handleOpenFollowers = async () => {
      await loadFollowersList()
      showFollowersDialog.value = true
    }
    
    // 打开关注列表
    const handleOpenFollowing = async () => {
      await loadFollowingList()
      showFollowingDialog.value = true
    }

    return {
      activeTab,
      showEditProfile,
      showFollowersDialog,
      showFollowingDialog,
      editFormRef,
      editForm,
      editRules,
      userVideos,
      userCollections,
      userLikes,
      userComments,
      followersList,
      followingList,
      currentUser,
      userAvatar,
      videoCount,
      likeCount,
      fansCount,
      followingCount,
      formatDate,
      formatTime,
      getUserName,
      getCommentCount,
      handleCloseEdit,
      handleUpdateProfile,
      handleOpenFollowers,
      handleOpenFollowing,
      goToVideoDetail,
      loadFollowStats
    }
  }
}
</script>

<style scoped>
.user-profile-container {
  background: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.user-header {
  display: flex;
  align-items: center;
  gap: 30px;
  background: white;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.user-basic-info {
  flex: 1;
}

.username {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #333;
}

.user-bio {
  margin: 0 0 20px 0;
  color: #666;
}

.user-stats {
  display: flex;
  gap: 40px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #00b42a;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.edit-profile-btn {
  align-self: flex-start;
}

.user-tabs {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.video-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  padding: 20px;
}

.video-card {
  cursor: pointer;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.video-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.video-cover {
  position: relative;
  margin-bottom: 10px;
}

.cover-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-radius: 4px;
}

.view-count {
  position: absolute;
  bottom: 5px;
  right: 5px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 3px;
}

.video-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.video-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #666;
}

.author {
  flex: 1;
}

.video-stats {
  display: flex;
  gap: 10px;
}

.video-stats span {
  display: flex;
  align-items: center;
  gap: 3px;
  font-size: 12px;
}

.comments-list {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.comment-item {
  background: #f9f9f9;
  padding: 15px;
  border-radius: 8px;
}

.comment-text {
  margin: 0 0 10px 0;
  line-height: 1.6;
  color: #333;
}

.comment-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.comment-time {
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
  gap: 5px;
}

.go-to-video-btn {
  padding: 5px 10px;
  background: #00b42a;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.go-to-video-btn:hover {
  background: #00a62a;
}

.edit-form {
  width: 100%;
}

/* 用户列表样式 */
.user-list {
  max-height: 400px;
  overflow-y: auto;
}

.user-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 16px;
}

.user-details {
  flex: 1;
}

.user-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.user-bio {
  font-size: 14px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .video-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .user-header {
    flex-direction: column;
    text-align: center;
  }
  
  .edit-profile-btn {
    align-self: center;
  }
  
  .video-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .cover-image {
    height: 160px;
  }
}

@media (max-width: 480px) {
  .video-grid {
    grid-template-columns: 1fr;
  }
}
</style>